package com.cm.sys.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.cm.sys.framework.application.ApiResponseCode;
import com.cm.sys.framework.execption.BusinessException;
import com.cm.sys.framework.utils.DateUtil;
import com.cm.sys.framework.utils.JsonUtil;
import com.cm.sys.framework.utils.PageList;
import com.cm.sys.system.dao.BusinessInfoMapper;
import com.cm.sys.system.dao.LogConditionMapper;
import com.cm.sys.system.dao.MenuMapper;
import com.cm.sys.system.entity.BusinessInfo;
import com.cm.sys.system.entity.BusinessTree;
import com.cm.sys.system.entity.LogCondition;
import com.cm.sys.system.entity.Menu;
import com.cm.sys.system.enums.ApprovalStatus;
import com.cm.sys.system.service.BusinessService;

/***
 * 创建业务线的接口
 * 
 * @author yxq18
 * @date 2019/12/17
 */
@Service
public class BusinessServiceImpl implements BusinessService {

    private static final Logger logger = LoggerFactory.getLogger(BusinessServiceImpl.class);

    @Resource
    private BusinessInfoMapper businessInfoMapper;

    @Autowired
    private PageList pageList;

    @Autowired
    private MenuMapper menuMapper;
    
    @Autowired
    private LogConditionMapper logConditionMapper;

    @Override
    public BusinessInfo saveBusinessInfo(JSONObject args) {

        BusinessInfo business = new BusinessInfo();

        Integer parentId = JsonUtil.getInt(args, "parentId");

        logger.info("===========创建业务线的接口======【{}】=============", args);
        business.setApprovalStatus(ApprovalStatus.SUBMIT.getCode());
        business.setBusinessName(JsonUtil.getString(args, "businessName"));
        business.setCreateTime(DateUtil.getTimestamp());
        business.setUpdateTime(DateUtil.getTimestamp());
        business.setMenuId(JsonUtil.getInt(args, "menuId"));
        business.setParentId(parentId);
        if (parentId.equals(0)) {// 表示模块
            business.setLocalhostAccount("0");
            business.setLocalhostDirectory("0");
            business.setLocalhostIp("0");
            business.setLocalhostPassword("0");
        } else {// 表示机器
            business.setLocalhostAccount(JsonUtil.getString(args, "localhostAccount"));
            business.setLocalhostDirectory(JsonUtil.getString(args, "localhostDirectory"));
            business.setLocalhostIp(JsonUtil.getString(args, "localhostIp"));
            business.setLocalhostPassword(JsonUtil.getString(args, "localhostPassword"));
        }
        businessInfoMapper.insert(business);
        return business;
    }

    @Override
    public int delBusinessInfo(JSONObject args, Integer userId) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public BusinessInfo updateBusinessInfo(JSONObject args, Integer businessInfoId) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Map<String, Object> selectBusiness(Integer pageIndex, Integer pageSize, String search) {

        pageList.initPage(pageIndex, pageSize);

        List<Map> list = businessInfoMapper.selectBusiness(search);
        Map<String, Object> map = pageList.getData(list, Map.class);
        logger.info("用户列表查询的入参==================【{}】===============", map);
        return map;

    }

    @Override
    public Menu saveMenu(JSONObject args) {

        Menu menu = new Menu();

        Integer parentId = JsonUtil.getInt(args, "parentId", 0);
        Integer sortInt = JsonUtil.getInt(args, "sortInt");
        Integer isShow = JsonUtil.getInt(args, "isShow");
        String parentName = JsonUtil.getString(args, "parentName");
        String route = JsonUtil.getString(args, "route");
        String icon = JsonUtil.getString(args, "icon");

        menu.setParentId(parentId);
        menu.setSortInt(sortInt);
        menu.setParentName(parentName);
        menu.setRoute(route);
        menu.setIcon(icon);
        menu.setIsShow(isShow);
        menu.setReviewStatus(1);// 新加业务线申请中
        Integer id = null;
        // 排除路由相同的
        id = menuMapper.selectRoute(menu.getRoute());
        if (id != null) {
            throw new BusinessException(ApiResponseCode.MENUROTE_ERROR.getCode(),
                ApiResponseCode.MENUROTE_ERROR.getMessage());
        }
        // 剔除重复菜单名id
        Integer dataParentName = menuMapper.selectParentName(menu.getParentName());
        if (dataParentName != null) {
            throw new BusinessException(ApiResponseCode.MENUPARENTNAME_EOOR.getCode(),
                ApiResponseCode.MENUPARENTNAME_EOOR.getMessage());
        }
        menu.setCreateTime(DateUtil.getTimestamp());
        menu.setUpdateTime(DateUtil.getTimestamp());
        menuMapper.insert(menu);

        return menu;
    }

    @Override
    public List<BusinessTree> selectBusinessInfo(Integer menuId) {
        List<BusinessTree> list = businessInfoMapper.selectAll(menuId);

        return (List<BusinessTree>)builTree(list);
    }

    // 建立树形结构
    public List<BusinessTree> builTree(List<BusinessTree> list) {
        List<BusinessTree> treeMenus = new ArrayList<BusinessTree>();
        for (BusinessTree menuNode : getRootNode(list)) {
            menuNode = buildChilTree(menuNode, list);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }

    // 递归，建立子树形结构
    private BusinessTree buildChilTree(BusinessTree pNode, List<BusinessTree> list) {
        List<BusinessTree> chilMenus = new ArrayList<BusinessTree>();
        for (BusinessTree menuNode : list) {
            if (menuNode.getParentId().equals(pNode.getBusinessId())) {
                chilMenus.add(buildChilTree(menuNode, list));
            }
        }
        pNode.setChildren(chilMenus);
        return pNode;
    }

    // 获取根节点
    @SuppressWarnings("unlikely-arg-type")
    private List<BusinessTree> getRootNode(List<BusinessTree> list) {
        List<BusinessTree> rootMenuLists = new ArrayList<BusinessTree>();
        for (BusinessTree menuNode : list) {
            if (menuNode.getParentId().equals(0)) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }

	@Override
	public void saveCondition(JSONObject args, Integer menuId) {
		LogCondition condition = new LogCondition();
		condition.setMenuId(menuId);
		condition.setFileType(JsonUtil.getString(args, "fileType"));
		condition.setRunningNumber(JsonUtil.getString(args, "runningNumber"));
		condition.setRunningPrefix(JsonUtil.getString(args, "runningPrefix"));
		condition.setDateTimeFormat(JsonUtil.getString(args, "dateTimeFormat"));
		logConditionMapper.insert(condition);
	}

}
